﻿/**
 * 2011-12-11
 */
package com.nbm.oa;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GraphicsEnvironment;
import java.awt.MenuItem;
import java.awt.Point;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import org.apache.http.client.ClientProtocolException;

import com.nbm.http.Httpclient;

/**
 * @author KevinLin
 * @version 1.0
 */
public class Tuopan extends JFrame implements Runnable
{
        private static final long serialVersionUID = 1L;
        /** 托盘图标 */
        private TrayIcon trayIcon = null;
        /** 本操作系统托盘的实例 */
        private SystemTray tray = null;
        /** 主面板 */
        private JPanel jPanel = null;
        /** 系统支持托盘标签 */
        private JLabel jLabel = null;
        /** 登陆面板 */
        private JPanel jPLogin = null;
        /** 用户名标签 */
        private JLabel jLPassword = null;
        /** 用户名输入框 */
        public static JTextField jTFName = null;
        /** 密码标签 */
        private JLabel jLName = null;
        /** 密码输入框 */
        public static JPasswordField jFPassword = null;
        /** 下面板 */
        private JPanel jPS = null;
        /** 最小化托盘按钮 */
        private JButton jBMin = null;
        /** 登录按钮 */
        private JButton jBLogin = null;
        /** 数据滚动面板 */
        private JScrollPane jScrollPane = null;
        /** 数据表 */
        private JTable jTable = null;
        /** 托盘状态 */
        boolean trayState = false;
        /** json数据 */
        String json = null;
        /** 未读消息数 */
        String count = null;
        /** 发送者 */
        String sender = null;
        /** 消息发送时间 */
        String date = null;
        /** 消息内容 */
        String content = null;
        /** 表数据 */
        Object[][] data = new Object[1][3];
        /** 表头字段 */
        String[] fields =
        { "发送者", "内容", "发送时间" };
        /** 线程 */
        private Thread t;

        /** 构造函数 */
        public Tuopan()
        {
                super();
                initialize();
        }

        /** 初始化 */
        private void initialize()
        {
                this.setSize(new Dimension(400, 300));
                this.setResizable(false); // 大小不可变
                this.setTitle("环评");
                this.setContentPane(getJPanel());
                // 判断是否支持托盘
                if (SystemTray.isSupported())
                {
                        this.tray();
                }
                this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                this.setVisible(true);
                t = new Thread(this);
                t.start();
        }

        /**
         * 托盘相关代码
         */
        private void tray()
        {
                jLabel.setText("本操作系统支持托盘");
                jBMin.setEnabled(true);
                tray = SystemTray.getSystemTray(); // 获得本操作系统托盘的实例
                ImageIcon icon = new ImageIcon("0.gif"); // 将要显示到托盘中的图标
                PopupMenu pop = new PopupMenu(); // 构造一个右键弹出式菜单
                MenuItem exit = new MenuItem("EXIT");
                trayIcon = new TrayIcon(icon.getImage(), "环评", pop);
                // 1.TrayIcon有三个构造 TrayIcon(Image image) 用“图标”来构造
                // 2.TrayIcon(Image image, String tooltip) 用“图标”和“ToolTip”构造
                // 3.TrayIcon(Image image,String tooltip, PopupMenu
                // popup)用“图标”，“ToolTip”，“弹出菜单”来构造一个托盘图标

                /** 最小化按钮监听器，添加托盘， 窗口不可见 */
                jBMin.addActionListener(new ActionListener()
                {
                        public void actionPerformed(ActionEvent e)
                        {
                                try
                                {
                                        tray.add(trayIcon); // 将托盘图标添加到系统的托盘实例中
                                        setVisible(false); // 使窗口不可视
                                        trayState = true;// 托盘线程开启
                                } catch (AWTException ex)
                                {
                                        ex.printStackTrace();
                                }
                        }
                });
                /** 添加鼠标监听器，当鼠标在托盘图标上双击时，默认显示窗口 */
                trayIcon.addMouseListener(new MouseAdapter()
                {
                        public void mouseClicked(MouseEvent e)
                        {
                                if (e.getClickCount() == 2)
                                { // 鼠标双击
                                        tray.remove(trayIcon); // 从系统的托盘实例中移除托盘图标
                                        setVisible(true); // 显示窗口
                                        trayState = false;// 托盘线程关闭
                                }
                        }
                });
                exit.addActionListener(new ActionListener()
                { // 点击“退出演示”菜单后推出程序

                        public void actionPerformed(ActionEvent e)
                        {
                                System.exit(0); // 退出程序
                        }
                });
                pop.add(exit);// 加入右键弹出菜单
        }

        /**
         * 主面板布局
         * 
         * @return javax.swing.JPanel
         */
        private JPanel getJPanel()
        {
                if (jPanel == null)
                {
                        jPanel = new JPanel();
                        jPanel.setLayout(new BorderLayout());
                        jLabel = new JLabel();
                        jLabel.setText("本操作系统不支持托盘");
                        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
                        jPanel.add(getJPLogin(), BorderLayout.NORTH);
                        jPanel.add(getJPS(), BorderLayout.SOUTH);
                        jPanel.add(getJScrollPane(), BorderLayout.CENTER);
                }
                return jPanel;
        }

        /**
         * 登录面板布局
         * 
         * @return javax.swing.JPanel
         */
        private JPanel getJPLogin()
        {
                if (jPLogin == null)
                {
                        jPLogin = new JPanel();
                        jPLogin.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));// （居中，列间距，行间距
                        // jPLogin.setPreferredSize(new Dimension(100, 35));
                        jLName = new JLabel();
                        jLName.setText("用户名：");
                        jLPassword = new JLabel();
                        jLPassword.setText("密    码：");
                        jPLogin.add(jLName, null);
                        jPLogin.add(getJTFName(), null);
                        jPLogin.add(jLPassword, null);
                        jPLogin.add(getJTFPassword(), null);
                        jPLogin.add(getJBLogin(), null);
                }
                return jPLogin;
        }

        /**
         * 用户名输入框
         * 
         * @return javax.swing.JTextField
         */
        private JTextField getJTFName()
        {
                if (jTFName == null)
                {
                        jTFName = new JTextField();
                        jTFName.setPreferredSize(new Dimension(100, 22));
                }
                return jTFName;
        }

        /**
         * 密码输入框
         * 
         * @return javax.swing.JTextField
         */
        private JPasswordField getJTFPassword()
        {
                if (jFPassword == null)
                {
                        jFPassword = new JPasswordField();
                        jFPassword.setPreferredSize(new Dimension(100, 22));
                        jFPassword.setEchoChar('*');
                }
                return jFPassword;
        }

        /**
         * 状态面板初始化
         * 
         * @return javax.swing.JPanel
         */
        private JPanel getJPS()
        {
                if (jPS == null)
                {
                        jPS = new JPanel();
                        jPS.setLayout(new BoxLayout(getJPS(), BoxLayout.X_AXIS));
                        jPS.add(jLabel, null);
                        jPS.add(getJBMin(), null);
                }
                return jPS;
        }

        /**
         * 最小化托盘按钮初始化
         * 
         * @return javax.swing.JButton
         */
        private JButton getJBMin()
        {
                if (jBMin == null)
                {
                        jBMin = new JButton("最小化到托盘");
                }
                return jBMin;
        }

        /**
         * 登录按钮初始化
         * 
         * @return javax.swing.JButton
         */
        private JButton getJBLogin()
        {
                if (jBLogin == null)
                {
                        jBLogin = new JButton("登录");
                        jBLogin.setPreferredSize(new Dimension(60, 22));
                        jBLogin.addMouseListener(new java.awt.event.MouseAdapter()
                        {
                                public void mouseClicked(java.awt.event.MouseEvent e)
                                {
                                        try
                                        {
                                                json = Httpclient.HttpLogin(jTFName.getText(),
                                                                jFPassword.getText());
                                                System.out.println("json:" + json);
                                                String[] a = null;
                                                String[] b = null;
                                                String[] c = null;
                                                String[] d = null;
                                                String[] f = null;
                                                String[] g = null;
                                                String[] h = null;
                                                a = json.split("\"ID:");
                                                b = a[0].split(",");
                                                c = b[0].split("count\":");
                                                d = a[1].split(",senddate:");
                                                f = d[0].split(",content:");
                                                g = d[1].split("\",");
                                                h = f[0].split("sender:");
                                                count = c[1];
                                                sender = h[1];
                                                content = f[1];
                                                date = g[0];
                                                jTable.setValueAt(sender, 0, 0);
                                                jTable.setValueAt(content, 0, 1);
                                                jTable.setValueAt(date, 0, 2);
                                        } catch (ClientProtocolException e1)
                                        {
                                                e1.printStackTrace();
                                        } catch (IOException e1)
                                        {
                                                e1.printStackTrace();
                                        }
                                }
                        });

                }
                return jBLogin;
        }

        /**
         * This method initializes jScrollPane
         * 
         * @return javax.swing.JScrollPane
         */
        private JScrollPane getJScrollPane()
        {
                if (jScrollPane == null)
                {
                        jScrollPane = new JScrollPane();
                        jScrollPane.setViewportView(getJTable());
                }
                return jScrollPane;
        }

        /**
         * 数据表定义
         * 
         * @return javax.swing.JTable
         */
        private JTable getJTable()
        {
                if (jTable == null)
                {
                        jTable = new JTable(data, fields);// (data, fields);
                        jTable.setEnabled(false);// 不可编辑
                }
                return jTable;
        }

        public static void main(String[] args)
        {
                Tuopan frame = new Tuopan();
                // 居中
                Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
                int windowWidth = frame.getWidth();
                int windowHeight = frame.getHeight();
                // set position and size
                frame.setBounds(center.x - windowWidth / 2, center.y - windowHeight / 2,
                                windowWidth, windowHeight);
        }

        /*
         * java.lang.Runnable#run()
         */
        public void run()
        {
                String update = null;// 未读消息更新对比
                while (true)
                {
                        // System.out.println("1:" + update);
                        if (trayState == true && count != null && count != "0")
                        {
                                // System.out.println("2:" + count);
                                if (update != count)
                                {
                                        trayIcon.displayMessage("您有" + count + "条新消息", content,
                                                        TrayIcon.MessageType.INFO);
                                        update = count;
                                        // System.out.println(q + "!=" + count);
                                } else
                                {
                                        try
                                        {
                                                // 闪动消息的空白时间
                                                Thread.sleep(500);
                                                this.trayIcon.setImage(new ImageIcon("").getImage());

                                                // 闪动消息的提示图片
                                                Thread.sleep(500);
                                                ImageIcon icon = new ImageIcon("0.gif");

                                                // 将要显示到托盘中的图标
                                                this.trayIcon.setImage(icon.getImage());
                                        } catch (InterruptedException e)
                                        {
                                                e.printStackTrace();
                                        }
                                }
                        } else
                        {
                                try
                                {
                                        Thread.sleep(1000);
                                        // System.out.println(q + "==" + count);
                                } catch (InterruptedException e)
                                {
                                        e.printStackTrace();
                                }
                        }
                }
        }
}
